<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item field="value1" label="织布单号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.zhizaocode" @press-enter="huiche" />
            </a-form-item>

            <a-form-item field="value3" label="坯布编号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.pibubianhao" @press-enter="huiche" />
            </a-form-item>

            <a-form-item field="value1" label="坯布名称">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                v-model="pageData.pibumingcheng" @press-enter="huiche" />
            </a-form-item>

            <a-form-item field="value2" label="机台号">
              <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder="" v-model="pageData.jitaihao"
                @press-enter="huiche" />
            </a-form-item>

            <a-form-item field="value1" label="日期">
              <a-date-picker  popup-container="html"  class="bacClass" v-model="pageData.jianyanriqi" :style="{ width: '200px' }"
                @press-enter="huiche" />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar class="gesture" :items="pageData.btnList" @select="selectHandler" @export="exports" @exportAll="exportAll" @fhzy="fhzy">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" :suppressCopyRowsToClipboard="true" class="ag-theme-alpine"
          :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1" @FilterChanged="FilterChangeds">
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size @change="PageSize"
      @page-size-change="change1" style="justify-content: center" />
    <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
      :width="400" :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
      @cancel="pageData.showAdd = false">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label-col-flex="80px" label="编号" field="brandCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandCode" @blur="inputBlur" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="品牌名称" field="brandName"
            :rules="[{ required: true, message: '品牌名称必填' }]" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandName" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="布类类型" field="clothClass"
            :rules="[{ required: true, message: '布类类型必填' }]" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html"  class="bacClass" :loading="loading" placeholder="" @search="handleSearch1"
              v-model="dataForm.clothClass" :filter-option="false" allow-search allow-clear @focus="focusSel1">
              <a-option v-for="item in pageData.typeList" :value="item">{{ item }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark" /> -->
            <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear show-word-limit />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
// 引入

import dayjs from 'dayjs'
interface BrandInfo {
  id: any
  brandCode: string
  brandName: string
  clothClass: string
  remark: string
  deleteState: number | string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

export default {
  name: 'MachineProductCondition',

  setup(props: any, { emit }) {
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)

    function doRefresh() {
      var obj = { page: page.value, size: size.value }
      if (pageData.zhizaocode != '') {
        obj['planOrderCode'] = pageData.zhizaocode
      }
      if (pageData.jitaihao != '') {
        obj['machineCode'] = pageData.jitaihao
      }
      if (pageData.jianyanriqi != '') {
        obj['date'] = pageData.jianyanriqi
      }
      if (pageData.pibubianhao != '') {
        obj['greyCode'] = pageData.pibubianhao
      }
      if (pageData.pibumingcheng != '') {
        obj['greyName'] = pageData.pibumingcheng
      }
      var bangbupishu = 0
      var bangbuweight = 0
      var yanhoupishu = 0
      var yanhouweight = 0
      var cibuweight = 0
      var koumishu = 0
      pageData.pageLoading = true
      post({
        url: '/product/statement/getMachineProduction',
        data: obj,
      })
        .then(({ data, code }: any) => {
          sessionStorage.setItem('wsnm', JSON.stringify(data))
          if (code === 200) {
            table.handleSuccess(data.data)
            gridOption.value.setFilterModel(null)
            // 查询方法改

            gridOption.value.setRowData(data.data)

            total.value = data.total
            data.data.map((o: any) => {
              o.buttonMeterNum = o.buttonMeterNum == undefined ? '' : o.buttonMeterNum
              o.colorName = o.colorName == undefined ? '' : o.colorName
              o.machineCode = o.machineCode == undefined ? '' : o.machineCode
              o.machineTypeName = o.machineTypeName == undefined ? '' : o.machineTypeName
              o.coordinate = o.coordinate == undefined ? '' : o.coordinate
              o.orderDepartment = o.orderDepartment == undefined ? '' : o.orderDepartment
              o.posteriorHorseNum = o.posteriorHorseNum == undefined ? '' : o.posteriorHorseNum
              o.customName = o.customName == undefined ? '' : o.customName
              o.greyName = o.greyName == undefined ? '' : o.greyName
              o.clothWeight = o.clothWeight == undefined ? '' : o.clothWeight
              o.greyCode = o.greyCode == undefined ? '' : o.greyCode
              o.firm = o.firm == undefined ? '' : o.firm
              o.horseNum = o.horseNum == undefined ? '' : o.horseNum
              o.posteriorWeight = o.posteriorWeight == undefined ? '' : o.posteriorWeight
              o.time = o.time == undefined ? '' : o.time
              o.workDrum = o.workDrum == undefined ? '' : o.workDrum
              o.planOrderCode = o.planOrderCode == undefined ? '' : o.planOrderCode
              o.businessType = o.businessType == undefined ? '' : o.businessType
              o.fabricWeight = o.fabricWeight == undefined ? '' : o.fabricWeight

              bangbupishu = bangbupishu + Number(o.horseNum)
              bangbuweight = bangbuweight + Number(o.clothWeight)
              yanhoupishu = yanhoupishu + Number(o.posteriorHorseNum)
              yanhouweight = yanhouweight + Number(o.posteriorWeight)
              cibuweight = cibuweight + Number(o.fabricWeight)
              koumishu = koumishu + Number(o.buttonMeterNum)
            })

            var newRows = [
              {
                buttonMeterNum: koumishu,
                colorName: '',
                machineCode: '',
                machineTypeName: '',
                coordinate: '',
                orderDepartment: '',
                posteriorHorseNum: yanhoupishu,
                customName: '',
                greyName: '',
                clothWeight: bangbuweight,
                greyCode: '',
                firm: '',
                horseNum: bangbupishu,
                posteriorWeight: yanhouweight,
                time: '',
                workDrum: '',
                planOrderCode: '',
                businessType: '',
                fabricWeight: cibuweight,
              },
            ]
            gridOption.value.setPinnedBottomRowData(newRows)
            pageData.hejishuzu = newRows as any
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'firm',
        dataIndex: 'firm',
        width: 150,
      },

      {
        title: '机台号',
        key: 'machineCode',
        dataIndex: 'machineCode',
        width: 150,
      },
      {
        title: '织布单号',
        key: 'planOrderCode',
        dataIndex: 'planOrderCode',
        width: 150,
      },
      {
        title: '下单部门',
        key: 'orderDepartment',
        dataIndex: 'orderDepartment',
        width: 150,
      },
      {
        title: '位置号',
        key: 'coordinate',
        dataIndex: 'coordinate',
        width: 150,
      },
      {
        title: '坯布编号',
        key: 'greyCode',
        dataIndex: 'greyCode',
        width: 150,
      },
      {
        title: '坯布名称',
        key: 'greyName',
        dataIndex: 'greyName',
        width: 150,
      },
      {
        title: '颜色',
        key: 'colorName',
        dataIndex: 'colorName',
        width: 150,
      },
      {
        title: '机台机型',
        key: 'machineTypeName',
        dataIndex: 'machineTypeName',
        width: 150,
      },
      {
        title: '客户名称',
        key: 'customName',
        dataIndex: 'customName',
        width: 200,
      },
      {
        title: '业务类型',
        key: 'businessType',
        dataIndex: 'businessType',
        width: 200,
      },
      {
        title: '订单针筒',
        key: 'workDrum',
        dataIndex: 'workDrum',
        width: 200,
      },
      {
        title: '磅布匹数',
        key: 'horseNum',
        dataIndex: 'horseNum',
        width: 200,
      },
      {
        title: '磅布重量',
        key: 'clothWeight',
        dataIndex: 'clothWeight',
        width: 200,
      },
      {
        title: '验后匹数',
        key: 'posteriorHorseNum',
        dataIndex: 'posteriorHorseNum',
        width: 200,
      },
      {
        title: '验后重量',
        key: 'posteriorWeight',
        dataIndex: 'posteriorWeight',
        width: 200,
      },
      {
        title: '次布重量',
        key: 'fabricWeight',
        dataIndex: 'fabricWeight',
        width: 200,
      },
      {
        title: '扣米数',
        key: 'buttonMeterNum',
        dataIndex: 'buttonMeterNum',
        width: 200,
      },

      {
        title: '日期',
        key: 'time',
        dataIndex: 'time',
        width: 200,
      },
      // {
      //     title: "删除状态",
      //     key: "deleteState",
      //     dataIndex: "deleteState",
      //     width: 100,
      //     slotName: "deleteState",
      //     fixed: 'right'
      // },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'

        obj['cellRenderer'] = {
          template: `<a-tag color="#ff7d00" class="gesture" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      hejishuzu: []
      pibubianhao: any
      pibubianhaolist: []
      pibumingcheng: any
      pibumingchenglist: []
      jitaihao: any
      jitaihaolist: []
      jianyanriqi: any
      zhizaocode: any
      zhizaocodelist: any[]
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增品牌资料',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      hejishuzu: [],
      pibubianhao: '',
      pibubianhaolist: [],
      pibumingcheng: '',
      pibumingchenglist: [],
      jianyanriqi: '',
      jitaihao: '',
      jitaihaolist: [],
      zhizaocode: '',
      zhizaocodelist: [] as any,
    })

    interface gcType {
      id: any
      company: any
    }

    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ brandName: '', deleteState: 0 })
    }
    //下拉数据
    const options1 = ref<any>(pageData.pibubianhaolist)
    const loading1 = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { greyCode: value }
        loading1.value = true

        selCxAll(ob)
        options1.value = pageData.pibubianhaolist
        loading1.value = false
      } else {
        options1.value = []
      }
    }

    //下拉框查询 布料类型
    //下拉框查询 坯布编号
    function selCxAll(val: any) {
      post({
        url: 'product/Rawmaterial/getGreyDrop',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.pibubianhaolist = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    onMounted(() => {
      pageData.jianyanriqi = dayjs(new Date()).format("YYYY-MM-DD")
      // 切换tap到本页面执行的方法
      emitter.on('BrandInfo', () => {
        // selCxAll1({});
        doRefresh()
      })
    })
    let cxbl = ''
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {
      selCxAll({ clothClass: '' })
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }

      pageData.showAdd = true
      pageData.sideTitle = '新增品牌资料'
    }
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      brandName: '',
      clothClass: '',
      deleteState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      brandCode: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }

    let formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          formRef.value?.validate().then((err) => {
            if (!err) {
              pageData.pageLoading = true
              if (pageData.sideTitle === '新增品牌资料') {
                post({
                  url: 'product/Brand/insert',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false

                      Message.success({
                        content: '新增成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                    doRefresh()
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              } else {
                post({
                  url: 'product/Brand/update',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false
                      Message.success({
                        content: '修改成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              }
            }
          })
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }

      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'product/Brand/deleteList',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }

    let curobj = null
    const editHandler = (record: BrandInfo) => {
      curobj = record
      //selCxAll1({ key: "" })
      dataForm.brandCode = record.brandCode
      dataForm.brandName = record.brandName
      dataForm.clothClass = record.clothClass
      dataForm.remark = record.remark
      dataForm.id = record.id
      pageData.sideTitle = '修改品牌资料'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.brandCode = dataForm.brandCode.toUpperCase()
    }
    //导出
    const exports = () => {
      var zongshuzu = [] as any
      gridOption.value.getSelectedRows().forEach(function (o: any) {
        zongshuzu.push(o)
      })
      pageData.hejishuzu.forEach((o: any) => {
        zongshuzu.push(o)
      })
      localStorage.setItem('daocu', JSON.stringify(zongshuzu))
      //
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        // gridOption.value.getSelectedRows().forEach(function(o:any){
        //     idList.push(o['id'])
        // })
        zongshuzu.forEach(function (o: any) {
          idList.push(o['id'])
        })
        //将表头拼接出来
        let head =
          '<th>车间</th><th>机台号</th><th>计划单号</th><th>下单部门</th><th>位置号</th><th>坯布编号</th><th>坯布名称</th><th>颜色</th><th>机台机型</th><th>客户名称</th><th>业务类型</th><th>订单针筒</th><th>磅布匹数</th><th>磅布重量</th>'
        head += '<th>验后匹数</th><th>验后重量</th><th>次布重量</th><th>扣米数</th><th>日期</th>'
        //拿到当前表格数据与勾选的行做筛选
        // let nowRow = table.dataList.filter(function (o) {
        //     return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
        // })
        let nowRow = zongshuzu.filter(function (o) {
          return (
            zongshuzu
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        var bangbupishu = 0
        var bangbuzhongliang = 0
        var yhpishu = 0
        var yhzhongliang = 0
        var cibuzhongliang = 0
        var koumishu = 0
        nowRow.forEach(function (o, index) {
          if (index != nowRow.length - 1) {
            bangbupishu = bangbupishu + o['horseNum']
            bangbuzhongliang = bangbuzhongliang + o['clothWeight']
            yhpishu = yhpishu + o['posteriorHorseNum']
            yhzhongliang = yhzhongliang + o['posteriorWeight']
            cibuzhongliang = cibuzhongliang + o['fabricWeight']
            koumishu = koumishu + o['buttonMeterNum']
          } else {
            o['horseNum'] = bangbupishu
            o['clothWeight'] = bangbuzhongliang
            o['posteriorHorseNum'] = yhpishu
            o['posteriorWeight'] = yhzhongliang
            o['fabricWeight'] = cibuzhongliang
            o['buttonMeterNum'] = koumishu
          }
          body += '<tr><td>' + o['firm'] + '</td>'
          body += '<td>' + o['machineCode'] + '</td>'
          body += '<td>' + o['planOrderCode'] + '</td>'
          body += '<td>' + o['orderDepartment'] + '</td>'
          body += '<td>' + o['coordinate'] + '</td>'
          body += '<td>' + o['greyCode'] + '</td>'
          body += '<td>' + o['greyName'] + '</td>'
          body += '<td>' + o['colorName'] + '</td>'
          body += '<td>' + o['machineTypeName'] + '</td>'
          body += '<td>' + o['customName'] + '</td>'
          body += '<td>' + o['businessType'] + '</td>'
          body += '<td>' + o['workDrum'] + '</td>'
          body += '<td>' + o['horseNum'] + '</td>'
          body += '<td>' + o['clothWeight'] + '</td>'
          body += '<td>' + o['posteriorHorseNum'] + '</td>'
          body += '<td>' + o['posteriorWeight'] + '</td>'
          body += '<td>' + o['fabricWeight'] + '</td>'
          body += '<td>' + o['buttonMeterNum'] + '</td>'
          body += '<td>' + o['time'] + '</td>'
          body += '</tr>'
        })
        tableToXlsx(head, '机台产量动态表', body)
        console.log(table)
      }
    }

    const exportAll = () => {
      var obj = {}
      if (pageData.zhizaocode != '') {
        obj['planOrderCode'] = pageData.zhizaocode
      }
      if (pageData.jitaihao != '') {
        obj['machineCode'] = pageData.jitaihao
      }
      if (pageData.jianyanriqi != '') {
        obj['date'] = pageData.jianyanriqi
      }
      if (pageData.pibubianhao != '') {
        obj['greyCode'] = pageData.pibubianhao
      }
      if (pageData.pibumingcheng != '') {
        obj['greyName'] = pageData.pibumingcheng
      }
      post({
        url: '/product/statement/exportGetMachineProduction',
        data: obj,
        responseType: 'blob'
      }).then((res) => {
        filedownload(res, '机台产量动态表.xlsx')
      });

    }
    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/product/Brand/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '品牌资料.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/product/Brand/importModelData', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    //下拉数据

    const options2 = ref<any>(pageData.pibumingchenglist)
    const loading2 = ref(false)
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = { grayFabricName: value }
        loading2.value = true

        selCxAll2(ob)
        options2.value = pageData.pibumingchenglist
        loading2.value = false
      } else {
        options2.value = []
      }
    }
    //下拉框查询 坯布名称
    function selCxAll2(val: any) {
      post({
        url: 'product/Rawmaterial/getGreyDrop',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.pibumingchenglist = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const options4 = ref<any>(pageData.jitaihaolist)
    const loading4 = ref(false)
    const handleSearch4 = (value: any) => {
      if (value) {
        const ob = { machineCode: value }
        loading4.value = true

        selCxAll4(ob)
        options4.value = pageData.jitaihaolist
        loading4.value = false
      } else {
        options4.value = []
      }
    }
    //下拉框查询 机台号
    function selCxAll4(val: any) {
      post({
        url: 'planSingle/machine/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");

          pageData.jitaihaolist = data
          //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    function selCxAll5(val: any) {
      post({
        url: 'planSingle/planOrder/getDropInfo',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");

          pageData.zhizaocodelist = data
          //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll({ greyCode: '' })
    }
    const focusSel2 = () => {
      selCxAll2({ grayFabricName: '' })
    }
    const focusSel4 = () => {
      selCxAll4({ machineCode: '' })
    }

    const focusSel5 = () => {
      selCxAll5({ weaveCode: '' })
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('ppzl.cx')) {
      pageData.btnList.push('查询')
    }

    if (permissionStore.hasPermisson('ppzl.dc')) {
      pageData.btnList.push('导出')
      pageData.btnList.push('全部导出')
    }
    if (permissionStore.hasPermisson('ppzl.dr')) {
      pageData.btnList.push('返回主页')
    }
    if (permissionStore.hasPermisson('ppzl.xg')) {
      pageData.isEdit = true
    }
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const fhzy = () => {
      emit('takebiaoji', 0)
      //localStorage.setItem('vvvv',props.biaoji)
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const huiche = () => {
      doRefresh()
    }
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)

    const FilterChangeds = (params: any) => {
      let data: any = {
        data:[]
      }
      params.api.forEachNodeAfterFilter((row: any) => {
        data.data.push(row.data)
      })
      var bangbupishu = 0
      var bangbuweight = 0
      var yanhoupishu = 0
      var yanhouweight = 0
      var cibuweight = 0
      var koumishu = 0
      data.data.map((o: any) => {
        o.buttonMeterNum = o.buttonMeterNum == undefined ? '' : o.buttonMeterNum
        o.colorName = o.colorName == undefined ? '' : o.colorName
        o.machineCode = o.machineCode == undefined ? '' : o.machineCode
        o.machineTypeName = o.machineTypeName == undefined ? '' : o.machineTypeName
        o.coordinate = o.coordinate == undefined ? '' : o.coordinate
        o.orderDepartment = o.orderDepartment == undefined ? '' : o.orderDepartment
        o.posteriorHorseNum = o.posteriorHorseNum == undefined ? '' : o.posteriorHorseNum
        o.customName = o.customName == undefined ? '' : o.customName
        o.greyName = o.greyName == undefined ? '' : o.greyName
        o.clothWeight = o.clothWeight == undefined ? '' : o.clothWeight
        o.greyCode = o.greyCode == undefined ? '' : o.greyCode
        o.firm = o.firm == undefined ? '' : o.firm
        o.horseNum = o.horseNum == undefined ? '' : o.horseNum
        o.posteriorWeight = o.posteriorWeight == undefined ? '' : o.posteriorWeight
        o.time = o.time == undefined ? '' : o.time
        o.workDrum = o.workDrum == undefined ? '' : o.workDrum
        o.planOrderCode = o.planOrderCode == undefined ? '' : o.planOrderCode
        o.businessType = o.businessType == undefined ? '' : o.businessType
        o.fabricWeight = o.fabricWeight == undefined ? '' : o.fabricWeight

        bangbupishu = bangbupishu + Number(o.horseNum)
        bangbuweight = bangbuweight + Number(o.clothWeight)
        yanhoupishu = yanhoupishu + Number(o.posteriorHorseNum)
        yanhouweight = yanhouweight + Number(o.posteriorWeight)
        cibuweight = cibuweight + Number(o.fabricWeight)
        koumishu = koumishu + Number(o.buttonMeterNum)
      })

      var newRows = [
        {
          buttonMeterNum: koumishu,
          colorName: '',
          machineCode: '',
          machineTypeName: '',
          coordinate: '',
          orderDepartment: '',
          posteriorHorseNum: yanhoupishu,
          customName: '',
          greyName: '',
          clothWeight: bangbuweight,
          greyCode: '',
          firm: '',
          horseNum: bangbupishu,
          posteriorWeight: yanhouweight,
          time: '',
          workDrum: '',
          planOrderCode: '',
          businessType: '',
          fabricWeight: cibuweight,
        },
      ]
      gridOption.value.setPinnedBottomRowData(newRows)
    }
    return {
      FilterChangeds,
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      inputBlur,
      exports,
      exportAll,
      focusSel,
      downloadHandler,
      importHandler,
      options1,
      loading1,
      options2,
      options4,
      loading2,
      loading4,
      handleSearch1,
      handleSearch4,
      focusSel1,
      handleSearch2,
      focusSel2,
      focusSel4,
      focusSel5,
      headerShow,
      handleChange,
      gridReady,
      fhzy,
    }
  },
  props: {
    biaoji: Number,
  },

  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped>
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>